<!-- Jinja2 Template File -->
{% extends "base.html" %}

{% block title %}管理面板 - EI Power问题管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-gear"></i> 管理员面板</h2>
            <span class="badge bg-danger fs-6">管理员权限</span>
        </div>
    </div>
</div>

<!-- 今日提交状态概览 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-people"></i> 今日用户提交状态</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    {% for user in users_status %}
                    <div class="col-md-6 col-lg-4 mb-3">
                        <div class="card border-0 {% if user.feedback_count >= 3 %}bg-success bg-opacity-10{% elif user.feedback_count > 0 %}bg-warning bg-opacity-10{% else %}bg-danger bg-opacity-10{% endif %}">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-1">{{ user.name }}</h6>
                                        <small class="text-muted">主邮箱: {{ user.email }}</small>
                                        {% if user.backup_email %}
                                        <br><small class="text-muted">备用邮箱: {{ user.backup_email }}</small>
                                        {% endif %}
                                    </div>
                                    <div class="text-end">
                                        <h4 class="mb-0 {% if user.feedback_count >= 3 %}text-success{% elif user.feedback_count > 0 %}text-warning{% else %}text-danger{% endif %}">
                                            {{ user.feedback_count }}/3
                                        </h4>
                                        {% if user.feedback_count >= 3 %}
                                            <span class="badge bg-success">已完成</span>
                                        {% elif user.feedback_count > 0 %}
                                            <span class="badge bg-warning">进行中</span>
                                        {% else %}
                                            <span class="badge bg-danger">未开始</span>
                                        {% endif %}
                                        <br>
                                        <div class="btn-group mt-1" role="group">
                                            <button class="btn btn-outline-primary btn-sm" 
                                                    onclick="sendManualReminder('{{ user.username }}', 'auto')" 
                                                    title="自动选择邮箱发送">
                                                <i class="bi bi-envelope"></i>
                                            </button>
                                            <button class="btn btn-outline-secondary btn-sm dropdown-toggle dropdown-toggle-split" 
                                                    data-bs-toggle="dropdown" 
                                                    title="选择邮箱发送">
                                                <span class="visually-hidden">选择邮箱</span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="#" onclick="sendManualReminder('{{ user.username }}', '{{ user.email }}')">发送到主邮箱<br><small class="text-muted">{{ user.email }}</small></a></li>
                                                {% if user.backup_email %}
                                                <li><a class="dropdown-item" href="#" onclick="sendManualReminder('{{ user.username }}', '{{ user.backup_email }}')">发送到备用邮箱<br><small class="text-muted">{{ user.backup_email }}</small></a></li>
                                                {% endif %}
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                {% set progress_class = 'bg-success' if user.feedback_count >= 3 else ('bg-warning' if user.feedback_count > 0 else 'bg-danger') %}
                                {% set progress_percent = (user.feedback_count / 3 * 100)|round %}
                                <div class="progress mt-2" style="height: 8px;">
                                    <div class="progress-bar {{ progress_class }}" 
                                         style="width: {{ progress_percent }}%;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 问题管理 -->
<div class="row">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-list-task"></i> 问题管理</h5>
            </div>
            <div class="card-body">
                <!-- 选项卡导航 -->
                <ul class="nav nav-tabs mb-3" id="feedbackTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="pending-tab" data-bs-toggle="tab" data-bs-target="#pending" type="button" role="tab">
                            <i class="bi bi-clock"></i> 待处理问题 
                            <span class="badge bg-primary ms-1">{{ pending_feedback|length }}</span>
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="resolved-tab" data-bs-toggle="tab" data-bs-target="#resolved" type="button" role="tab">
                            <i class="bi bi-check-circle"></i> 已解决问题 
                            <span class="badge bg-success ms-1">{{ resolved_feedback|length }}</span>
                        </button>
                    </li>
                </ul>
                
                <!-- 选项卡内容 -->
                <div class="tab-content" id="feedbackTabContent">
                    <!-- 待处理问题选项卡 -->
                    <div class="tab-pane fade show active" id="pending" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">待处理问题列表</h6>
                            <div>
                                <button class="btn btn-outline-primary btn-sm" onclick="filterFeedback('all')">
                                    全部 ({{ pending_feedback|length }})
                                </button>
                                <button class="btn btn-outline-warning btn-sm" onclick="filterFeedback('新问题')">
                                    新问题 ({{ pending_feedback|selectattr('status', 'equalto', '新问题')|list|length }})
                                </button>
                                <button class="btn btn-outline-info btn-sm" onclick="filterFeedback('处理中')">
                                    处理中 ({{ pending_feedback|selectattr('status', 'equalto', '处理中')|list|length }})
                                </button>
                            </div>
                        </div>
                        {% if pending_feedback %}
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th style="width: 12%;">编号</th>
                                            <th style="width: 10%;">提议人</th>
                                            <th style="width: 30%;">问题内容</th>
                                            <th style="width: 8%;">状态</th>
                                            <th style="width: 12%;">提交时间</th>
                                            <th style="width: 28%;">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="feedback-tbody">
                                        {% for feedback in pending_feedback %}
                                        <tr class="feedback-row" data-status="{{ feedback.status }}">
                                            <td><code class="small">{{ feedback.id }}</code></td>
                                            <td>
                                                <span class="badge bg-secondary">{{ feedback.name }}</span>
                                                <br><small class="text-muted">{{ feedback.username }}</small>
                                            </td>
                                            <td>
                                                <div class="text-truncate" style="max-width: 250px;" title="{{ feedback.content }}">
                                                    {{ feedback.content }}
                                                </div>
                                            </td>
                                            <td>
                                                {% if feedback.status == '新问题' %}
                                                    <span class="badge bg-primary">{{ feedback.status }}</span>
                                                {% elif feedback.status == '处理中' %}
                                                    <span class="badge bg-warning">{{ feedback.status }}</span>
                                                {% endif %}
                                            </td>
                                            <td>
                                                <small class="text-muted">
                                                    {{ feedback.created_at.strftime('%m-%d %H:%M') if feedback.created_at else '' }}
                                                </small>
                                            </td>
                                            <td>
                                                <button class="btn btn-outline-info btn-sm me-1" 
                                                        data-id="{{ feedback.id }}"
                                                        data-username="{{ feedback.username|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-content="{{ feedback.content|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-status="{{ feedback.status }}"
                                                        data-revised="{{ (feedback.revised_proposal or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-comment="{{ (feedback.admin_comment or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-handler="{{ feedback.handler or '' }}"
                                                        data-has-answer="{{ feedback.has_answer or 0 }}"
                                                        data-answer="{{ (feedback.answer or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        onclick="viewFeedbackFromData(this)"
                                                        title="查看详情">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="btn btn-outline-primary btn-sm me-1" 
                                                        data-id="{{ feedback.id }}"
                                                        data-status="{{ feedback.status }}"
                                                        data-revised="{{ (feedback.revised_proposal or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-comment="{{ (feedback.admin_comment or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-has-answer="{{ feedback.has_answer or 0 }}"
                                                        data-answer="{{ (feedback.answer or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        onclick="editFeedbackFromData(this)"
                                                        title="编辑问题">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <button class="btn btn-outline-danger btn-sm" 
                                                        data-id="{{ feedback.id }}"
                                                        data-username="{{ feedback.username|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        onclick="deleteFeedback(this)"
                                                        title="删除问题">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        {% else %}
                            <div class="text-center py-4">
                                <i class="bi bi-check-circle display-1 text-success"></i>
                                <h5 class="text-muted mt-3">所有问题已处理完成</h5>
                    <p class="text-muted">当前没有待处理的问题</p>
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 已解决问题选项卡 -->
                    <div class="tab-pane fade" id="resolved" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">已解决问题列表</h6>
                            <div class="d-flex align-items-center gap-2">
                                <span class="text-muted">共 {{ resolved_feedback|length }} 个已解决问题</span>
                                {% if resolved_feedback %}
                                <a href="{{ url_for('export_resolved_feedback') }}" class="btn btn-success btn-sm">
                                    <i class="bi bi-download"></i> 导出CSV
                                </a>
                                {% endif %}
                            </div>
                        </div>
                        
                        {% if resolved_feedback %}
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th style="width: 12%;">编号</th>
                                            <th style="width: 10%;">提议人</th>
                                            <th style="width: 30%;">问题内容</th>
                                            <th style="width: 8%;">状态</th>
                                            <th style="width: 12%;">解决时间</th>
                                            <th style="width: 28%;">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for feedback in resolved_feedback %}
                                        <tr>
                                            <td><code class="small">{{ feedback.id }}</code></td>
                                            <td>
                                                <span class="badge bg-secondary">{{ feedback.name }}</span>
                                                <br><small class="text-muted">{{ feedback.username }}</small>
                                            </td>
                                            <td>
                                                <div class="text-truncate" style="max-width: 250px;" title="{{ feedback.content }}">
                                                    {{ feedback.content }}
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge bg-success">{{ feedback.status }}</span>
                                            </td>
                                            <td>
                                                <small class="text-muted">
                                                    {{ feedback.updated_at.strftime('%m-%d %H:%M') if feedback.updated_at else '' }}
                                                </small>
                                            </td>
                                            <td>
                                                <button class="btn btn-outline-info btn-sm me-1" 
                                                        data-id="{{ feedback.id }}"
                                                        data-username="{{ feedback.username|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-content="{{ feedback.content|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-status="{{ feedback.status }}"
                                                        data-revised="{{ (feedback.revised_proposal or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-comment="{{ (feedback.admin_comment or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        data-handler="{{ feedback.handler or '' }}"
                                                        data-has-answer="{{ feedback.has_answer or 0 }}"
                                                        data-answer="{{ (feedback.answer or '')|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        onclick="viewFeedbackFromData(this)"
                                                        title="查看详情">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="btn btn-outline-danger btn-sm" 
                                                        data-id="{{ feedback.id }}"
                                                        data-username="{{ feedback.username|replace('"', '&quot;')|replace("'", "&#39;") }}"
                                                        onclick="deleteFeedback(this)"
                                                        title="删除问题">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        {% else %}
                            <div class="text-center py-4">
                                <i class="bi bi-archive display-1 text-muted"></i>
                                <h5 class="text-muted mt-3">暂无已解决问题</h5>
                    <p class="text-muted">已解决的问题将显示在这里</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查看反馈模态框 -->
<div class="modal fade" id="viewFeedbackModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-file-text"></i> 问题详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>编号：</strong>
                        <code id="view-id"></code>
                    </div>
                    <div class="col-md-6">
                        <strong>提交人：</strong>
                        <span id="view-username" class="badge bg-secondary"></span>
                    </div>
                </div>
                
                <div class="mb-3">
                    <strong>问题内容：</strong>
                    <div class="bg-light p-3 rounded mt-2" id="view-content"></div>
                </div>
                
                <div class="mb-3" id="view-answer-section" style="display: none;">
                    <strong>提交者的答案/解决方案：</strong>
                    <div class="bg-primary bg-opacity-10 p-3 rounded mt-2" id="view-answer"></div>
                </div>
                
                <div class="mb-3">
                    <strong>当前状态：</strong>
                    <span id="view-status-badge"></span>
                </div>
                
                <div class="mb-3" id="view-revised-section" style="display: none;">
                    <strong>修正问题：</strong>
                    <div class="bg-info bg-opacity-10 p-3 rounded mt-2" id="view-revised-proposal"></div>
                </div>
                
                <div class="mb-3" id="view-comment-section" style="display: none;">
                    <strong>处理意见：</strong>
                    <div class="bg-success bg-opacity-10 p-3 rounded mt-2" id="view-admin-comment"></div>
                </div>
                
                <div class="row" id="view-handler-section" style="display: none;">
                    <div class="col-md-6">
                        <strong>处理人：</strong>
                        <span id="view-handler" class="text-muted"></span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑反馈模态框 -->
<div class="modal fade" id="editFeedbackModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil"></i> 处理问题</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ url_for('update_feedback') }}">
                <div class="modal-body">
                    <input type="hidden" id="edit-feedback-id" name="feedback_id">
                    
                    <div class="mb-3">
                        <label for="edit-status" class="form-label">
                            <i class="bi bi-flag"></i> 处理状态 <span class="text-danger">*</span>
                        </label>
                        <select class="form-select" id="edit-status" name="status" required>
                            <option value="新问题">新问题</option>
                            <option value="处理中">处理中</option>
                            <option value="已解决">已解决</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit-revised-proposal" class="form-label">
                            <i class="bi bi-lightbulb"></i> 修正问题
                        </label>
                        <textarea class="form-control" id="edit-revised-proposal" name="revised_proposal" rows="3" 
                                placeholder="如有需要，请提供修正后的问题内容..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="edit-has-answer" name="has_answer" value="1" checked>
                            <label class="form-check-label" for="edit-has-answer">
                                <i class="bi bi-lightbulb-fill"></i> 我有答案或解决方案
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3" id="answer-section">
                        <label for="edit-answer" class="form-label">
                            <i class="bi bi-check-circle"></i> 答案/解决方案
                        </label>
                        <textarea class="form-control" id="edit-answer" name="answer" rows="4" 
                                placeholder="请提供具体的答案或解决方案..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit-admin-comment" class="form-label">
                            <i class="bi bi-chat-text"></i> 处理意见
                        </label>
                        <textarea class="form-control" id="edit-admin-comment" name="admin_comment" rows="4" 
                                placeholder="请填写处理意见、解决方案或相关说明..."></textarea>
                    </div>
                    
                    <div class="alert alert-info border-0" role="alert">
                        <h6><i class="bi bi-info-circle"></i> 处理指南</h6>
                        <ul class="mb-0 small">
                            <li><strong>新问题：</strong>刚收到的反馈，尚未开始处理</li>
                            <li><strong>处理中：</strong>正在分析或解决中，可填写进展说明</li>
                            <li><strong>已解决：</strong>问题已解决或建议已采纳，需填写处理结果</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-circle"></i> 保存更新
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('Admin page loaded successfully');
    console.log('Bootstrap available:', typeof bootstrap !== 'undefined');
    
    // 检查所有删除按钮
    const deleteButtons = document.querySelectorAll('[onclick*="deleteFeedback"]');
    console.log('Found delete buttons:', deleteButtons.length);
});

// 筛选反馈
function filterFeedback(status) {
    const rows = document.querySelectorAll('.feedback-row');
    
    rows.forEach(row => {
        if (status === 'all' || row.dataset.status === status) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
    
    // 更新按钮状态
    document.querySelectorAll('.btn-outline-primary, .btn-outline-warning, .btn-outline-info').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
}

// 查看反馈详情
function viewFeedback(id, username, content, status, revisedProposal, adminComment, handler, hasAnswer, answer) {
    document.getElementById('view-id').textContent = id;
    document.getElementById('view-username').textContent = username;
    document.getElementById('view-content').textContent = content;
    
    // 状态徽章
    const statusBadge = document.getElementById('view-status-badge');
    if (status === '新问题') {
            statusBadge.innerHTML = '<span class="badge bg-primary">新问题</span>';
    } else if (status === '处理中') {
        statusBadge.innerHTML = '<span class="badge bg-warning">处理中</span>';
    } else if (status === '已解决') {
        statusBadge.innerHTML = '<span class="badge bg-success">已解决</span>';
    }
    
    // 答案/解决方案
    const answerSection = document.getElementById('view-answer-section');
    if (hasAnswer && (hasAnswer === '1' || hasAnswer === 1 || hasAnswer === true) && answer && answer.trim()) {
        document.getElementById('view-answer').textContent = answer;
        answerSection.style.display = 'block';
    } else {
        answerSection.style.display = 'none';
    }
    
    // 修正问题
    const revisedSection = document.getElementById('view-revised-section');
    if (revisedProposal && revisedProposal.trim()) {
        document.getElementById('view-revised-proposal').textContent = revisedProposal;
        revisedSection.style.display = 'block';
    } else {
        revisedSection.style.display = 'none';
    }
    
    // 处理意见
    const commentSection = document.getElementById('view-comment-section');
    if (adminComment && adminComment.trim()) {
        document.getElementById('view-admin-comment').textContent = adminComment;
        commentSection.style.display = 'block';
    } else {
        commentSection.style.display = 'none';
    }
    
    // 处理人
    const handlerSection = document.getElementById('view-handler-section');
    if (handler && handler.trim()) {
        document.getElementById('view-handler').textContent = handler;
        handlerSection.style.display = 'block';
    } else {
        handlerSection.style.display = 'none';
    }
    
    const modal = new bootstrap.Modal(document.getElementById('viewFeedbackModal'));
    modal.show();
}

// 从按钮数据属性查看反馈详情
function viewFeedbackFromData(button) {
    var id = button.getAttribute('data-id');
    var username = button.getAttribute('data-username');
    var content = button.getAttribute('data-content');
    var status = button.getAttribute('data-status');
    var revised = button.getAttribute('data-revised');
    var comment = button.getAttribute('data-comment');
    var handler = button.getAttribute('data-handler');
    var hasAnswer = button.getAttribute('data-has-answer');
    var answer = button.getAttribute('data-answer');
    
    viewFeedback(id, username, content, status, revised, comment, handler, hasAnswer, answer);
}

// 编辑反馈
function editFeedback(id, status, revisedProposal, adminComment, hasAnswer, answer) {
    document.getElementById('edit-feedback-id').value = id;
    document.getElementById('edit-status').value = status;
    document.getElementById('edit-revised-proposal').value = revisedProposal || '';
    document.getElementById('edit-admin-comment').value = adminComment || '';
    
    // 设置has_answer复选框状态
    const hasAnswerCheckbox = document.getElementById('edit-has-answer');
    hasAnswerCheckbox.checked = hasAnswer === '1' || hasAnswer === 1 || hasAnswer === true;
    
    // 设置answer字段值
    document.getElementById('edit-answer').value = answer || '';
    
    // 控制答案输入框的显示/隐藏
    toggleAnswerSection();
    
    const modal = new bootstrap.Modal(document.getElementById('editFeedbackModal'));
    modal.show();
}

// 从按钮数据属性编辑反馈
function editFeedbackFromData(button) {
    var id = button.getAttribute('data-id');
    var status = button.getAttribute('data-status');
    var revised = button.getAttribute('data-revised');
    var comment = button.getAttribute('data-comment');
    var hasAnswer = button.getAttribute('data-has-answer');
    var answer = button.getAttribute('data-answer');
    
    editFeedback(id, status, revised, comment, hasAnswer, answer);
}

// 控制答案输入框的显示/隐藏
function toggleAnswerSection() {
    const hasAnswerCheckbox = document.getElementById('edit-has-answer');
    const answerSection = document.getElementById('answer-section');
    
    if (hasAnswerCheckbox.checked) {
        answerSection.style.display = 'block';
    } else {
        answerSection.style.display = 'none';
        // 清空答案内容
        document.getElementById('edit-answer').value = '';
    }
}

// 删除问题
function deleteFeedback(button) {
    try {
        console.log('deleteFeedback called with button:', button);
        const feedbackId = button.getAttribute('data-id');
        const username = button.getAttribute('data-username');
        console.log('feedbackId:', feedbackId, 'username:', username);
        
        // 显示删除确认对话框
        showDeleteConfirmModal(feedbackId, username, button);
    } catch (error) {
        console.error('Error in deleteFeedback:', error);
        showAlert('danger', '删除功能出错: ' + error.message);
    }
}

// 显示删除确认模态框
function showDeleteConfirmModal(feedbackId, username, button) {
    try {
        console.log('showDeleteConfirmModal called with:', feedbackId, username, button);
    // 创建模态框HTML
    const modalHtml = `
        <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title text-danger"><i class="bi bi-exclamation-triangle"></i> 确认删除问题</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-warning" role="alert">
                            <strong>警告：</strong>此操作不可撤销！删除后将自动通知提议人。
                        </div>
                        <p><strong>问题编号：</strong>#${feedbackId}</p>
                        <p><strong>提议人：</strong>${username}</p>
                        
                        <div class="mb-3">
                            <label for="deletionReason" class="form-label">删除原因（可选）：</label>
                            <textarea class="form-control" id="deletionReason" rows="3" 
                                    placeholder="请简要说明删除此问题的原因，此信息将发送给提议人..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteBtn" data-feedback-id="${feedbackId}" data-username="${username}">
                            <i class="bi bi-trash"></i> 确认删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模态框
    const existingModal = document.getElementById('deleteConfirmModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 添加新模态框到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
    
    // 存储按钮引用
    window.currentDeleteButton = button;
    
    // 添加确认删除按钮的事件监听器
    document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
        const feedbackId = this.getAttribute('data-feedback-id');
         const username = this.getAttribute('data-username');
         confirmDelete(feedbackId, username);
     });
     
     console.log('Modal created and event listener added successfully');
    } catch (error) {
        console.error('Error in showDeleteConfirmModal:', error);
        showAlert('danger', '显示删除确认对话框时出错: ' + error.message);
    }
}

// 确认删除
function confirmDelete(feedbackId, username) {
    try {
        console.log('confirmDelete called with:', feedbackId, username);
        const reason = document.getElementById('deletionReason').value.trim();
        const button = window.currentDeleteButton;
        console.log('Delete reason:', reason, 'Button:', button);
    
    if (!button) {
        showAlert('danger', '操作失败，请重试');
        return;
    }
    
    const originalHtml = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i>';
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
    modal.hide();
    
    // 发送删除请求
    const requestBody = reason ? { reason: reason } : {};
    
    fetch(`/api/delete_feedback/${feedbackId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers.get('content-type'));
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return response.json();
        } else {
            return response.text().then(text => {
                console.error('Non-JSON response:', text);
                throw new Error('服务器返回了非JSON响应');
            });
        }
    })
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            // 从表格中移除该行
            const row = button.closest('tr');
            row.style.transition = 'opacity 0.3s';
            row.style.opacity = '0';
            setTimeout(() => {
                row.remove();
            }, 300);
        } else {
            showAlert('danger', data.message);
            button.innerHTML = originalHtml;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '删除失败，请稍后重试');
        button.innerHTML = originalHtml;
        button.disabled = false;
    });
    } catch (error) {
        console.error('Error in confirmDelete:', error);
        showAlert('danger', '确认删除时出错: ' + error.message);
        if (window.currentDeleteButton) {
            window.currentDeleteButton.disabled = false;
            window.currentDeleteButton.innerHTML = '<i class="bi bi-trash"></i>';
        }
    }
}

// 发送手动邮件提醒
function sendManualReminder(username, targetEmail = 'auto') {
    let confirmMessage = `确定要向 ${username} 发送邮件提醒吗？`;
    if (targetEmail !== 'auto') {
        confirmMessage = `确定要向 ${username} 的邮箱 ${targetEmail} 发送邮件提醒吗？`;
    }
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    const button = event.target.closest('button');
    const originalHtml = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i>';
    
    const requestBody = {
        user_identifier: username
    };
    
    if (targetEmail !== 'auto') {
        requestBody.target_email = targetEmail;
    }
    
    fetch('/send_manual_reminder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示成功消息
            showAlert('success', data.message);
            button.innerHTML = '<i class="bi bi-check-circle"></i>';
            setTimeout(() => {
                button.innerHTML = originalHtml;
                button.disabled = false;
            }, 2000);
        } else {
            showAlert('danger', data.message);
            button.innerHTML = originalHtml;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '发送失败，请稍后重试');
        button.innerHTML = originalHtml;
        button.disabled = false;
    });
}

// 显示提示消息
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 3000);
}

// 自动刷新页面数据
setInterval(function() {
    // 可以添加AJAX请求来更新数据，这里暂时不实现
}, 300000); // 5分钟刷新一次

// 页面加载完成后添加事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 为has_answer复选框添加变化事件监听器
    const hasAnswerCheckbox = document.getElementById('edit-has-answer');
    if (hasAnswerCheckbox) {
        hasAnswerCheckbox.addEventListener('change', toggleAnswerSection);
        // 初始化答案输入框的显示状态
        toggleAnswerSection();
    }
});
</script>
{% endblock %}